// Decompiled by Jad v1.5.8e2. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://kpdus.tripod.com/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi space 
// Source File Name:   GSMServiceHTTPGateway.java

package cn.sendsms;

import java.io.IOException;
import java.net.*;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;

// Referenced classes of package cn.sendsms:
//			HTTPGateway, OutboundMessage, TimeoutException, GatewayException, 
//			MessageStatuses

public class GSMServiceHTTPGateway extends HTTPGateway
{

	private String username;
	private String password;
	private Object sync;

	public GSMServiceHTTPGateway(String id, String username, String password, Logger logger)
	{
		super(id, logger);
		this.username = username;
		this.password = password;
		attributes = 5;
		sync = new Object();
	}

	boolean sendMessage(OutboundMessage msg)
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		URL url = null;
		boolean ok = false;
		try
		{
			String file = "/api/send.php?login=" + username + "&pass=" + password + "&showid=1&rodzaj=1&podpis=" + msg.getFrom() + "&numer=" + msg.getRecipient().substring(1) + "&tekst=" + URLEncoder.encode(msg.getText(), "ISO-8859-1") + "";
			if (msg.getFrom() != null && msg.getFrom().length() != 0)
				file.concat("&podpis=" + URLEncoder.encode(msg.getFrom(), "ISO-8859-1"));
			url = new URL("http", "bramka.gsmservice.pl", file);
			List response;
			synchronized (sync)
			{
				response = HttpGet(url);
			}
			String first = (String)response.get(0);
			Matcher m = Pattern.compile("Status:(\\d+)(\\|(\\d+))?").matcher(first);
			if (m.matches())
			{
				msg.setRefNo(m.group(3));
				msg.setDispatchDate(new Date());
				int stat = Integer.parseInt(m.group(1));
				switch (stat)
				{
				case 3: // '\003'
				case 10: // '\n'
				case 13: // '\r'
					msg.setMessageStatus(MessageStatuses.SENT);
					ok = true;
					break;

				default:
					msg.setMessageStatus(MessageStatuses.FAILED);
					break;
				}
			} else
			{
				logError("Invalid response from provider");
			}
		}
		catch (MalformedURLException e)
		{
			logError("Malformed URL " + url);
		}
		catch (IOException e)
		{
			logError("I/O Error");
		}
		return ok;
	}

	void sendMessage(List msgList)
		throws TimeoutException, GatewayException, IOException, InterruptedException
	{
		for (int i = 0; i < msgList.size(); i++)
			sendMessage((OutboundMessage)msgList.get(i));

	}
}
